package ch.comtools.ssh;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class RemoteConsumerThread extends Thread {

	private SocketChannel channel;
    private Charset charset = Charset.forName("ISO-8859-1");
    private CharsetDecoder decoder = charset.newDecoder();

	/**
	 * @param channel
	 */
	public RemoteConsumerThread(SocketChannel channel) {
		this.channel = channel;
	}
	
	@Override
	public void run() {
		ByteBuffer buf = ByteBuffer.allocateDirect(8196);
		while(true) {
			try {
				// Read from socket
				buf.clear();
		        int numBytesRead = channel.read(buf);
		        if (numBytesRead == -1) {
		            // No more bytes can be read from the channel
		        	return;
		        } else {
		        	// Flip buffer to read
		        	buf.flip();
		            // Read the bytes from the buffer
		        	CharBuffer cb = decoder.decode(buf);
		        	System.out.println("buffer: " + cb.toString());
		        }
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
